package com.gz.mylife.util;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;

import com.gz.mylife.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.zl.smartmall.library.util.CrashHandler;

public class ImageUtils {

	private static final String TAG = ImageUtils.class.getSimpleName();

	/**
	 * 将图片圆角显示的函数,返回Bitmap
	 * @param bitmap
	 * @return
	 */
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap,float roundPx) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		// 根据原来图片大小画一个矩形
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		// 圆角弧度参数,数值越大圆角越大,甚至可以画圆形
		//final float roundPx = 24;

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		// 画出一个圆角的矩形
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		// 取两层绘制交集,显示上层
		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		// 显示图片
		canvas.drawBitmap(bitmap, rect, rect, paint);
		// 返回Bitmap对象
		return output;
	}
	
	public static Bitmap getRoundedCornerBitmap2(Bitmap bitmap) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		// 根据原来图片大小画一个矩形
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getWidth());
		final RectF rectF = new RectF(rect);
		// 圆角弧度参数,数值越大圆角越大,甚至可以画圆形
		//final float roundPx = 12;
		final float roundPx = bitmap.getWidth()/2;

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		// 画出一个圆角的矩形
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		// 取两层绘制交集,显示上层
		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
		// 显示图片
		canvas.drawBitmap(bitmap, rect, rect, paint);
		// 返回Bitmap对象
		return output;
	}
	

	/**
	 * through the rectangle zooming images
	 * 
	 * @param bitmap
	 *            expect being resized original picture
	 * @param width
	 *            expected width for bitmap
	 * @param height
	 *            expected height for bitmap
	 * @return
	 */
	public static Bitmap zoomBitmapByRect(Bitmap bitmap, int width, int height) {
		if (bitmap.isRecycled()) {
			return null;
		}
		final int bitmapWidth = bitmap.getWidth();
		final int bitmapHeight = bitmap.getHeight();

		if (width > 0 && height > 0) {

			final Bitmap.Config c = Bitmap.Config.ARGB_8888;
			final Bitmap thumb = Bitmap.createBitmap(width, height, c);
			final Canvas canvas = new Canvas();
			final Paint paint = new Paint();

			canvas.setBitmap(thumb);
			paint.setDither(false);
			paint.setFilterBitmap(true);
			Rect sBounds = new Rect();
			sBounds.set(0, 0, width, height);
			Rect sOldBounds = new Rect();
			sOldBounds.set(0, 0, bitmapWidth, bitmapHeight);
			canvas.drawBitmap(bitmap, sOldBounds, sBounds, paint);

			return thumb;
		}

		return bitmap;
	}

	/**
	 * through the Matirx zooming images
	 */
	public static Bitmap zoomBitmapByMatrix(Bitmap bitmap, int w, int h) {

		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		float scaleWidht = ((float) w / width);
		float scaleHeight = ((float) h / height);
		matrix.postScale(scaleWidht, scaleHeight);
		Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		return newbmp;

	}

	public static Bitmap drawable2Bitmap(Drawable drawable) {
		try {
			int width = drawable.getIntrinsicWidth();
			int height = drawable.getIntrinsicHeight();
			Bitmap.Config config = Bitmap.Config.ARGB_8888; // RGB565绘制会有黑边框
			Bitmap bitmap = Bitmap.createBitmap(width, height, config);
			Canvas canvas = new Canvas(bitmap);
			drawable.setBounds(0, 0, width, height);
			drawable.draw(canvas);
			return bitmap;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Bitmap view2Bitmap(View v) {
		v.clearFocus();
		v.setPressed(false);

		boolean willNotCache = v.willNotCacheDrawing();
		v.setWillNotCacheDrawing(false);

		// Reset the drawing cache background color to fully transparent
		// for the duration of this operation
		int color = v.getDrawingCacheBackgroundColor();
		v.setDrawingCacheBackgroundColor(0);

		if (color != 0) {
			v.destroyDrawingCache();
		}
		v.buildDrawingCache();
		Bitmap cacheBitmap = v.getDrawingCache();
		if (cacheBitmap == null) {
			return null;
		}

		Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

		// Restore the view
		v.destroyDrawingCache();
		v.setWillNotCacheDrawing(willNotCache);
		v.setDrawingCacheBackgroundColor(color);

		// Bitmap bitmap1 = setAlpha(bitmap, 100);

		return bitmap;
	}

	/**
	 * 生成圆角图片
	 * 
	 * @param bitmap
	 *            原始位图
	 * @return
	 */
	public static Bitmap GenerateRoundedCornerBitmap(Bitmap bitmap) {
		try {
			Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
					bitmap.getHeight(), Config.ARGB_8888);
			Canvas canvas = new Canvas(output);
			final Paint paint = new Paint();
			final Rect rect = new Rect(0, 0, bitmap.getWidth(),
					bitmap.getHeight());
			final RectF rectF = new RectF(new Rect(0, 0, bitmap.getWidth(),
					bitmap.getHeight()));
			final float roundPx = 60;
			paint.setAntiAlias(true);
			canvas.drawARGB(0x00, 0x00, 0x00, 0x00);
			// paint.setColor(Color.RED);
			canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
			paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));

			final Rect src = new Rect(0, 0, bitmap.getWidth(),
					bitmap.getHeight());

			canvas.drawBitmap(bitmap, src, rect, paint);
			return output;
		} catch (Exception e) {
			return bitmap;
		}
	}

	public static Bitmap compressBitmap(Resources res, int resId, int sampleSize) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;

		BitmapFactory.decodeResource(res, resId, options);

		options.inSampleSize = sampleSize;
		options.inJustDecodeBounds = false;
		Bitmap bitmap = BitmapFactory.decodeResource(res, resId, options);

		return bitmap;
	}
	
	public static Bitmap compressBitmap(String fileName, int sampleSize) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(fileName, options);

		options.inSampleSize = sampleSize;
		options.inJustDecodeBounds = false;
		Bitmap bitmap = BitmapFactory.decodeFile(fileName, options);

		return bitmap;
	}
	
	
//	public static Bitmap compressBitmap(Resources res, int resId) {
//		BitmapFactory.Options options = new BitmapFactory.Options();
//		options.inJustDecodeBounds = true;
//
//		BitmapFactory.decodeResource(res, resId, options);
//
//		int height = options.outHeight;
//		int width = options.outWidth;
//		if()
//		
//		options.inSampleSize = sampleSize;
//		options.inJustDecodeBounds = false;
//		Bitmap bitmap = BitmapFactory.decodeResource(res, resId, options);
//
//		return bitmap;
//	}

	public static Bitmap getViewBitmap(View v) {
		v.clearFocus();
		v.setPressed(false);

		boolean willNotCache = v.willNotCacheDrawing();
		v.setWillNotCacheDrawing(false);

		// Reset the drawing cache background color to fully transparent
		// for the duration of this operation
		int color = v.getDrawingCacheBackgroundColor();
		v.setDrawingCacheBackgroundColor(0);

		if (color != 0) {
			v.destroyDrawingCache();
		}
		v.buildDrawingCache();
		Bitmap cacheBitmap = v.getDrawingCache();

		if (cacheBitmap == null) {
			// Log.e(TAG, "failed getViewBitmap(" + v + ")", new
			// RuntimeException());
			return null;
		}

		Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

		// Restore the view
		v.destroyDrawingCache();
		v.setWillNotCacheDrawing(willNotCache);
		v.setDrawingCacheBackgroundColor(color);

		return bitmap;
	}
	
	public static Bitmap drawCircularBitmap(Bitmap bitmap){
	
		Bitmap circleBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
		BitmapShader shader = new BitmapShader (bitmap,  TileMode.CLAMP, TileMode.CLAMP);

		Paint paint = new Paint();
		paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		paint.setDither(false);
		paint.setFilterBitmap(true);
		paint.setShader(shader);

		//以后出现问题就是这里
//		float radius = bitmap.getWidth() > bitmap.getHeight() ? bitmap.getHeight() / 2 : bitmap.getWidth() / 2;
		Canvas c = new Canvas(circleBitmap);
		c.drawCircle(bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getWidth() / 2, paint);

//		CrashHandler.d("ImageUtils", "circel width " + bitmap.getWidth());
//		CrashHandler.d("ImageUtils", "circel height " + bitmap.getHeight());
//		CrashHandler.d("ImageUtils", "circel radius " + radius);
		return circleBitmap;
	}
	
	public static void unbindDrawables(View view) {
		if(view == null){
			return;
		}
		if (view.getBackground() != null) {
			view.getBackground().setCallback(null);
		}
		if(view instanceof ImageView){
			ImageView iv =(ImageView)view;
			if(iv.getDrawable()!=null) {
				iv.getDrawable().setCallback(null);
				iv.setImageDrawable(null);
				CrashHandler.d(TAG, "ImageView Drawable not null");
			}
		}
//		try {
//			if (view instanceof ViewGroup) {
//				for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
//					unbindDrawables(((ViewGroup) view).getChildAt(i));
//				}
//				((ViewGroup) view).removeAllViews();
//			}
//		} catch (Exception e) {
//
//		}
	}
	
	public static String getBigPictureUrl(String url){
		if(isBigPicture(url)){
			return url;
		}
		String bigUrl = url;
		Pattern p = Pattern.compile("\\/s\\/(s\\d+)?");
		Matcher matcher = p.matcher(url);
		if(matcher.find()){
			String temp = matcher.group();
			temp = temp.replaceFirst("s", "b");
			temp = temp.replaceFirst("s", "");
			bigUrl = matcher.replaceFirst(temp);
		}
		return bigUrl;
	}
	
	public static boolean isBigPicture(String url){
		if(url.matches(".*\\/b\\/.*")){
			return true;
		} else {
			return false;
		}
	}
	
	public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		bmp.compress(CompressFormat.PNG, 100, output);
		if (needRecycle) {
			bmp.recycle();
		}
		
		byte[] result = output.toByteArray();
		try {
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}

	
	public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {  
	    int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);  
	    int roundedSize;  
	    if (initialSize <= 8) {  
	        roundedSize = 1;  
	        while (roundedSize < initialSize) {  
	            roundedSize <<= 1;  
	        }  
	    } else {  
	        roundedSize = (initialSize + 7) / 8 * 8;  
	    }  
	    return roundedSize;  
	}
	
	private static int computeInitialSampleSize(BitmapFactory.Options options,int minSideLength, int maxNumOfPixels) {  
	    double w = options.outWidth;  
	    double h = options.outHeight;  
	    int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));  
	    int upperBound = (minSideLength == -1) ? 128 :(int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));  
	    if (upperBound < lowerBound) {  
	        // return the larger one when there is no overlapping zone.  
	        return lowerBound;  
	    }  
	    if ((maxNumOfPixels == -1) && (minSideLength == -1)) {  
	        return 1;  
	    } else if (minSideLength == -1) {  
	        return lowerBound;  
	    } else {  
	        return upperBound;  
	    }  
	} 
	
    public static void rotateImg(String path , float angle){
        Bitmap bitMap = BitmapFactory.decodeFile(path);
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        bitMap = Bitmap.createBitmap(bitMap ,0,0, bitMap .getWidth(), bitMap .getHeight(),matrix,true);//使用矩阵来构建旋转后的图片
        try {
			FileOutputStream fos = null;
			try{
				fos = new FileOutputStream(path);
				if (null != fos) {
					bitMap.compress(Bitmap.CompressFormat.PNG, 100, fos);
					fos.flush();
					fos.close();
				}
			}finally{
				if(bitMap!=null && !bitMap.isRecycled()){
					bitMap.recycle();
				}
			}
        }catch (Exception e) {
        	
		}
	}
	
	public static DisplayImageOptions buildCircleOptions() {
		return new DisplayImageOptions.Builder()
			.showImageOnLoading(R.color.transparent)
			.showImageOnFail(R.color.transparent)
			.showImageForEmptyUri(R.color.transparent)
			.resetViewBeforeLoading(true)
			.bitmapConfig(Bitmap.Config.ARGB_8888)
			.cacheInMemory(true)
			.cacheOnDisk(true)
			.imageScaleType(ImageScaleType.IN_SAMPLE_INT) // default
			.displayer(new CircularBitmapDisplayer())
			.build();
	}

	public static DisplayImageOptions buildTransparentOptions(){
		return new DisplayImageOptions.Builder()
        .resetViewBeforeLoading(true)
        .bitmapConfig(Bitmap.Config.ARGB_8888)
        .cacheInMemory(true)
        .cacheOnDisk(true)
        .showImageOnLoading(R.color.transparent)
        .showImageOnFail(R.color.transparent)
        .showImageForEmptyUri(R.color.transparent)
        .imageScaleType(ImageScaleType.EXACTLY)
        .build();
	}
}
